import ftp from 'ftp';
import { promises as fsPromises } from 'fs';
import fs from 'fs';
import path from 'path';

// FTP 配置信息
const ftpConfig = {
  host: '205.177.209.91',
  port: '21',
  user: 'benji',
  password: '123UGP!@osIB'
};

// 文件路径
const remoteFilePath = '/J1APP/JBOTHUpdate.json';
const localFilePath = path.join(process.cwd(), '/ftp/JBOTHUpdate.json');

const client = new ftp();

client.on('ready', function() {
  // 下载文件
  client.get(remoteFilePath, function(err, stream) {
    if (err) throw err;
    stream.once('close', async function() {
      // 更新文件内容
      await updateJsonFile(localFilePath);
      // 上传文件
      client.put(localFilePath, remoteFilePath, function(err) {
        if (err) throw err;
        console.log('File updated and uploaded successfully!');
        client.end();
      });
    });
    stream.pipe(fs.createWriteStream(localFilePath));
  });
});

// 连接到 FTP
client.connect(ftpConfig);

async function updateJsonFile(filePath) {
  const jsonPath = path.join(process.cwd(), './src/actions/Api.json');
  const jsonData = JSON.parse(await fsPromises.readFile(jsonPath, 'utf8'));

  const data = JSON.parse(fs.readFileSync(filePath, 'utf8'));
  data.versionCode = jsonData.versionCode;
  fs.writeFileSync(filePath, JSON.stringify(data, null, 2), 'utf8');
}
